<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="user_id" label="">
        <uni-easyinput placeholder="申请用户ID" v-model="formData.user_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="name" label="" required>
        <uni-easyinput placeholder="传承人姓名" v-model="formData.name"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="avator_image" label="">
        <uni-easyinput placeholder="非遗传人头像" v-model="formData.avator_image"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="phone" label="联系电话" required>
        <uni-easyinput placeholder="联系电话" v-model="formData.phone"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="email" label="" required>
        <uni-easyinput placeholder="电子邮箱" v-model="formData.email" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="title" label="" required>
        <uni-easyinput placeholder="职业头衔" v-model="formData.title"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="direction" label="" required>
        <uni-easyinput placeholder="主要传承方向" v-model="formData.direction"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="description" label="" required>
        <uni-easyinput placeholder="自我介绍" v-model="formData.description"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="level" label="" required>
        <uni-data-checkbox v-model="formData.level" :localdata="formOptions.level_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="certificate_image" label="">
        <uni-easyinput placeholder="证明材料图片" v-model="formData.certificate_image"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="apply_date" label="">
        <uni-datetime-picker return-type="timestamp" v-model="formData.apply_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="audit_status" label="">
        <picker @change="pickerChange($event, 'audit_status')" :range="formOptions.audit_status_data" :value="formOptions.audit_status_index">
          <view>{{formOptions.audit_status_data[formOptions.audit_status_index] || "请选择..."}}</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item name="reject_reason" label="">
        <uni-easyinput placeholder="拒绝原因，仅在status为2时有值" v-model="formData.reject_reason" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="audit_time" label="">
        <uni-datetime-picker return-type="timestamp" v-model="formData.audit_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="auditor_id" label="">
        <uni-easyinput placeholder="审核人ID" v-model="formData.auditor_id"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="honors" label="">
        <uni-data-checkbox :multiple="true" v-model="formData.honors"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="portfolio" label="">
        <uni-data-checkbox :multiple="true" v-model="formData.portfolio"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/intangible_master.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'intangible_master';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  function numberRange(start, end) {
    return Array.from(new Array(end + 1).keys()).slice(start);
  }

  export default {
    data() {
      let formData = {
        "user_id": "",
        "name": "",
        "avator_image": "",
        "phone": "",
        "email": "",
        "title": "",
        "direction": "",
        "description": "",
        "level": null,
        "certificate_image": "",
        "apply_date": null,
        "audit_status": 0,
        "reject_reason": "",
        "audit_time": null,
        "auditor_id": "",
        "honors": [],
        "portfolio": []
      }
      return {
        formData,
        formOptions: {
          "level_localdata": [
            {
              "text": "国家级",
              "value": 1
            },
            {
              "text": "省级",
              "value": 2
            },
            {
              "text": "市级",
              "value": 3
            },
            {
              "text": "县级",
              "value": 4
            },
            {
              "text": "其他",
              "value": 5
            }
          ],
          "audit_status_data": numberRange(0, 2),
          "audit_status_index": null
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      pickerChange(e, name) {
        this.formOptions[name + '_index'] = e.detail.value;
        this.formData[name] = this.formOptions[name + '_data'][e.detail.value];
        this.binddata(name, this.formData[name]);
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
